<template>
	<view class="container">
		<view v-if="isfetch">
			<view class="top-nav" v-if="lijiyuyue == '1'">
				<view
					class="flex f-align f-justifyB w100"
					v-if="addressInfo.gzbh"
					@click="selectGzbh"
				>
					<view class="flex f-column">
						<view class="flex mt10">
							<image
								src="../static/img/shouyudibiao@2x.png"
								style="width: 40rpx; height: 40rpx"
							></image>
							<text class="font28 gray333 ml10" style="width: 560rpx">{{
								addressInfo.text
							}}</text>
						</view>
					</view>
				</view>
				<view
					class="flex f-align f-justifyB w100"
					v-else
					@click="$api.toPage('./yuYueOrder?type=2')"
				>
					<text class="font28 gray333 bold">请选择服务点</text>
					<text class="font30 gray777 zlicon icon-right"></text>
				</view>
			</view>

			<view class="flex f-column order-item">
				<text class="font28 gray333 bold">选择服务</text>
				<view v-for="(item, index) in orderList" :key="index" class="item-list">
					<select-item
						ref="selectItem"
						:item="item"
						:index="index"
						@change="getUpdateNum"
					></select-item>
				</view>
			</view>

			<view
				class="info-box flex f-align f-justifyB mt30"
				@click="toPage('quan')"
			>
				<text class="font28 gray333">体验券</text>
				<view class="flex f-align">
					<view class="red-box green-box" v-if="ticketVal"
						>已使用{{ ticketVal }}元体验券</view
					>
					<view class="red-box" v-else-if="userInfo.isGetDiscounts == '已领取'"
						>有可使用的体验券</view
					>
					<view class="red-box" v-else>暂无体验券可用</view>
					<text class="font30 gray999 zlicon icon-right ml10"></text>
				</view>
			</view>
			<view class="info-box flex f-align f-justifyB" @click="toPage('cika')">
				<text class="font28 gray333">我的次卡</text>
				<view class="flex f-align">
					<view class="red-box green-box" v-if="cikaNum"
						>已使用{{ cikaNum }}张次卡</view
					>
					<view class="red-box" v-else-if="!userInfo.setUpNumber"
						>暂无次卡可用</view
					>
					<view class="red-box" v-else
						>有{{ userInfo.setUpNumber }}张可使用的次卡</view
					>
					<text class="font30 gray999 zlicon icon-right ml10"></text>
				</view>
			</view>
			<view v-if="lijiyuyue == '2'">
				<view class="info-box flex f-align">
					<text class="font28 gray333">客户姓名</text>
					<view class="customerName">
						<input
							placeholder="请输入客户姓名"
							class="font28"
							v-model="consignee"
						/>
					</view>
				</view>
				<view class="info-box flex f-align">
					<text class="font28 gray333">联系电话</text>
					<view class="customerName">
						<input
							placeholder="请输入联系电话"
							class="font28"
							v-model="mobile"
						/>
					</view>
				</view>
				<view class="info-box flex f-align">
					<text class="font28 gray333">服务地址</text>
					<view class="customerName" @click="serviceAddress">
						<text class="font28" style="color: blue">{{ addresscontent }}</text>
					</view>
					<text class="font30 gray999 zlicon icon-right ml10"></text>
				</view>
				<view class="info-box flex f-align font28 gray333">
					<radio :checked="sechecked" @click="sechecked = !sechecked"
						>是否上门取送</radio
					>
				</view>
				<view class="info-box flex f-align f-center" v-if="sechecked">
					<text class="font28 gray333">上门时间</text>
					<view class="customerName" @click="changeLog">
						<!-- <text class="font28" style="color: blue;" v-if="single.length === 0">{{addresstime}}</text> -->
						<!-- <uni-datetime-picker type="datetime" v-model="datetimesingle" @change="changeLog" /> -->
						<view class="dateclass">
							<uni-datetime-picker
								v-model="single"
								:border="false"
								:clearIcon="false"
								>{{ addresstime }}</uni-datetime-picker
							>
						</view>
						<!-- 			<uni-datetime-picker type="datetime" returnType="date" v-model="datetimesingle" @change="changeLog" />
				 -->
					</view>
					<text class="font30 gray999 zlicon icon-right ml10"></text>
				</view>
			</view>
			<view v-else></view>

			<view class="f-center mt30">
				<icon
					type="success"
					size="20"
					:color="!isArgee ? '#C0C4CC' : ''"
					@click="isArgee = !isArgee"
				></icon>
				<text class="font24 gray999 ml20" @click="$api.toPage('./guize')"
					>同意《智能洗衣平台服务规则》</text
				>
			</view>
			<view class="flex f-column wash-box" v-if="washList.length > 0">
				<text class="font28 gray333 bold">洗护须知</text>
				<view
					class="flex f-column mt30"
					v-for="(item, index) in washList"
					:key="index"
				>
					<text class="font24 gray333">{{ index + 1 }}、{{ item.title }}</text>
					<text class="font22 gray999 mt10">{{ item.content }}</text>
				</view>
			</view>

			<view class="btn-group">
				<view class="con-btn flex f-align f-justifyB">
					<view class="flex f-align">
						<text class="font32 gray333">合计：</text>
						<text class="font24 red bold">￥</text>
						<text class="font40 red bold">{{ realMoney }}</text>
					</view>
					<view class="btn-box f-center" @click="payHandle">
						<text class="font32 white">确认支付</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 选择支付方式 -->
		<uni-popup ref="uniPopup" type="bottom">
			<view class="pay-box flex f-column f-align">
				<text class="font28 bold" style="margin-bottom: 60rpx"
					>请选择支付方式</text
				>
				<view class="box-item flex f-align f-justifyB" @click="vxPay('余额')">
					<view class="flex f-align">
						<image
							src="../static/img/yuepay.png"
							style="width: 60rpx; height: 52rpx"
						></image>
						<view class="flex f-column ml30">
							<text class="font32 bold">余额支付</text>
							<text
								class="font28 gray777"
								v-if="Number(userInfo.remainingSum) < realMoney"
								>余额不足，剩余 {{ userInfo.remainingSum }} 元</text
							>
						</view>
					</view>
					<view
						class="cz-btn f-center font24 white"
						v-if="Number(userInfo.remainingSum) < realMoney"
					>
						去充值
					</view>
					<view class="flex f-align" v-else>
						<text class="font28 gray777"
							>余额：￥{{ userInfo.remainingSum }}</text
						>
						<text
							class="zlicon icon-right font28 ml30"
							style="color: #524f4e"
						></text>
					</view>
				</view>
				<view class="box-item flex f-align f-justifyB" @click="vxPay('微信')">
					<view class="flex f-align">
						<image
							src="../static/img/vxpay.png"
							style="width: 60rpx; height: 52rpx"
						></image>
						<text class="font32 bold ml30">微信支付</text>
					</view>
					<text
						class="zlicon icon-right font28 ml30"
						style="color: #524f4e"
					></text>
				</view>
				<view class="f-center close-btn" @click="$refs.uniPopup.close()">
					<image
						src="../static/img/close.png"
						style="width: 26rpx; height: 26rpx"
					></image>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import selectItem from '@/components/selectItem.vue'
import { mapState } from 'vuex'
export default {
	data() {
		return {
			// consignee 客户姓名 mobile 联系电话 addressId 服务地址的选择 visitDate 上门时间 visit 选择是否上门取送
			consignee: '',
			sechecked: false,
			mobile: '',
			dddd: '',
			visitDate: '',
			visit: '',
			single: '',
			datetimesingle: '',
			range: ['2021-02-1', '2021-3-28'],
			datetimerange: [],
			start: Date.now() - 1000000000,
			end: Date.now() + 1000000000,
			addressInfo: {
				name: '智能洗衣',
				phone: '',
				text: '',
				gzbh: ''
			},
			orderList: [], // 订单源数据
			cikaSelectNum: 0, // 次卡选择数量
			orderOneList: [], // 订单拆分 加 排序
			isDiscounts: '未使用',
			ticketVal: 0, // 体验券数值
			isCart: 0, // 是否是购物车结算
			washList: [],
			isArgee: true,
			isfetch: true,
			flag: '', // 下单方式
			addressId: '',
			addresscontent: '请选择服务地址',
			addresstime: '请选择上门时间',
			noDiscountTotal: 0, // 不能使用优惠的衣子钱总数,
			lijiyuyue: ''
		}
	},
	components: {
		selectItem
	},
	onLoad(option) {
		if (option.isCart) {
			this.isCart = option.isCart
		}
		this.orderList = JSON.parse(uni.getStorageSync('submitInfo'))
		this.orderList.forEach((item) => {
			for (let i = 0; i < item.goodsNumber; i++) {
				if (item.isUseDiscounts == '是') {
					this.orderOneList.push(parseFloat(item.goodsMoney))
				} else {
					this.noDiscountTotal += parseFloat(item.goodsMoney)
				}
			}
		})
		this.orderOneList.sort(function (a, b) {
			return a - b
		})
		this.getWashList()
	},
	onShow() {
		this.lijiyuyue = uni.getStorageSync('lijiyuyue')
		console.log('getApp().globalData.gzbh')
		console.log(getApp().globalData.gzbh)
		// getApp().globalData.gzbh = "QN025648274"
		// QN025648274
		if (getApp().globalData.gzbh) {
			this.addressInfo.gzbh = getApp().globalData.gzbh
			this.dddd = getApp().globalData.gzbh
			this.getAddressList(this.dddd)
			this.flag = uni.getStorageSync('flag')
		} else {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					const { latitude = '', longitude = '' } = Object.assign({}, res)
					getApp().globalData.latitude = latitude
					getApp().globalData.longitude = longitude
					getApp().globalData.gzbh = ''

					this.$http
						.ajax({
							url: '/Cabinet/list',
							params: {
								gzbh: '',
								lat: latitude,
								lng: longitude
							}
						})
						.then((res) => {
							const { data = [] } = Object.assign({}, res)
							const [data0 = {}] = data.filter(
								(v) => v.cabinet05 - v.cabinet06 > 0
							)
							const { gzbh = '', phone = '', address = '' } = data0
							getApp().globalData.gzbh = gzbh

							this.addressInfo.gzbh = gzbh
							this.addressInfo.phone = phone
							this.addressInfo.text = address

							console.log(this.addressInfo, 90)
						})
				},
				fail: (err) => {
					this.$api.msg('位置获取失败')
					this.addressInfo.gzbh = ''
				}
			})
		}
	},
	mounted() {
		this.consignee = this.userInfo.userName
		this.mobile = this.userInfo.userPhone
	},
	watch: {
		single(newVal, oldVal) {
			// 监听 num 属性的数据变化
			// 作用 : 只要 num 的值发生变化,这个方法就会被调用
			// 第一个参数 : 新值
			// 第二个参数 : 旧值,之前的值
			console.log('oldVal:', oldVal)
			console.log('newVal:', newVal)
			this.addresstime = newVal
		}
	},

	computed: {
		// 次卡使用数量
		cikaNum() {
			if (this.isDiscounts == '已使用') {
				if (this.cikaSelectNum > this.totalInfo.discountNum - 1) {
					return this.totalInfo.discountNum - 1
				} else {
					return this.cikaSelectNum
				}
			} else {
				if (this.cikaSelectNum > this.totalInfo.discountNum) {
					return this.totalInfo.discountNum
				} else {
					return this.cikaSelectNum
				}
			}
		},
		// 实际支付金额
		realMoney() {
			let arr = this.orderOneList.slice(0)
			if (this.isDiscounts == '已使用') {
				arr[0] = this.ticketVal
				arr.splice(1, this.cikaNum)
			} else {
				arr.splice(0, this.cikaNum)
			}
			let money = 0
			arr.forEach((item) => {
				money += item
			})
			return (money + this.noDiscountTotal).toFixed(2)
		},
		// 订单最初的信息 总额 衣子总数量 衣子可以优惠的数量
		totalInfo() {
			let money = 0
			let num = 0
			let discountNum = 0
			this.orderList.forEach((item) => {
				num += item.goodsNumber
				money += item.goodsNumber * parseFloat(item.goodsMoney)
				if (item.isUseDiscounts == '是') {
					discountNum += item.goodsNumber
				}
			})
			return {
				money: money.toFixed(2),
				num,
				discountNum
			}
		},
		...mapState(['userInfo'])
	},
	methods: {
		changeLog(e) {
			console.log('----change事件:', e)
		},
		selectDDAddress(index) {
			var object = JSON.parse(index)
			this.addressId = object.id

			console.log('服务地址' + index + object.id)
			this.addresscontent =
				object.province +
				' ' +
				object.city +
				' ' +
				object.area +
				' ' +
				object.address
		},
		serviceAddress() {
			console.log('服务地址')
			this.$api.toPage('../pages_address/userAddress?type=1')
		},
		serviceTime() {
			console.log('服务时间')
		},
		selectGzbh() {
			if (this.flag == '扫码下单') return
			this.$api.toPage('./yuYueOrder?type=2')
		},
		getWashList() {
			this.$http
				.ajax({
					url: '/WashCareInstructions/list',
					params: {}
				})
				.then((res) => {
					if (res.code == 0) {
						this.washList = res.data
					}
				})
		},
		toPage(type) {
			if (!this.totalInfo.discountNum) {
				this.$api.msg('当前暂无可以使用体验券和次卡的套餐')
				return
			}

			if (type == 'cika') {
				if (!this.userInfo.setUpNumber) return
				this.$api.toPage(
					'./cardList?type=' + type + '&goodsNum=' + this.totalInfo.discountNum
				)
			} else {
				if (this.userInfo.isGetDiscounts != '已领取') return
				this.$api.toPage('./cardList?type=' + type)
			}
		},
		getUpdateNum(event) {
			this.orderList[event.index].goodsNumber = event.num
		},

		payHandle() {
			var that = this
			if (this.lijiyuyue == '1') {
				if (!getApp().globalData.gzbh) {
					this.$api.msg('请在上方选择服务点')
					return
				}
			}

			if (this.lijiyuyue == '2') {
				if (this.consignee.length === 0) {
					this.$api.msg('请输入客户姓名')
					return
				}
				if (this.mobile.length === 0) {
					this.$api.msg('请输入联系电话')
					return
				}
				if (this.addressId.length === 0) {
					this.$api.msg('请选择服务地址')
					return
				}
				if (that.sechecked) {
					if (this.single.length === 0) {
						this.$api.msg('请选择上门时间')
						return
					}
				}
			}

			if (!this.isArgee) {
				this.$api.msg('未同意智能洗衣服务规则')
				return
			}

			if (this.lijiyuyue == '1') {
				uni.showLoading({
					title: '正在检测箱门状态...',
					mask: true
				})
				this.$http
					.ajax({
						url: '/Box/selectGzbhStatus',
						params: {
							gzbh: getApp().globalData.gzbh,
							number: this.totalInfo.num
						}
					})
					.then((res) => {
						uni.hideLoading()
						if (res.code == 200) {
							this.$refs.uniPopup.open()
						} else {
							this.$api.msg(res.msg)
						}
					})
			} else {
				this.$refs.uniPopup.open()
			}
		},
		vxPay(payType) {
			if (
				payType == '余额' &&
				Number(this.userInfo.remainingSum) < this.realMoney
			) {
				this.$api.toPage('./myVIP')
				return
			}
			uni.showLoading({
				title: '请求中，请稍后...',
				mask: true
			})
			let _this = this
			let formData
			let arr = []
			let orderMoney = 0
			let goodsNumber = 0
			let flag = uni.getStorageSync('flag')
			this.orderList.forEach((item) => {
				orderMoney += item.goodsNumber * parseFloat(item.goodsMoney)
				goodsNumber += item.goodsNumber
				for (let i = 0; i < item.goodsNumber; i++) {
					arr.push({
						projectId: item.projectId,
						goodName: item.goodsName,
						projectName: item.projects
							.map((item) => item.projectName)
							.join(','),
						goodMoney: item.goodsMoney,
						goodsUrl: item.goodsUrl,
						isUseDiscounts: item.isUseDiscounts
					})
				}
			})

			// consignee 客户姓名 mobile 联系电话 addressId 服务地址的选择 visitDate 上门时间 visit 选择是否上门取送
			formData = {
				consignee: _this.consignee,
				mobile: _this.mobile,
				addressId: _this.addressId,
				visitDate: _this.single,
				visit: _this.sechecked ? '1' : '0',
				openId: uni.getStorageSync('openId'),
				orderDetail: JSON.stringify(arr),
				orderMoney: orderMoney.toFixed(2),
				goodsNumber: goodsNumber,
				amountPayable: this.realMoney,
				actualPayment: this.realMoney,
				isDiscounts: this.isDiscounts,
				taocanshuliang: this.cikaNum,
				type: this.isCart,

				gzbh: _this.lijiyuyue == '1' ? getApp().globalData.gzbh : 'QN25648266',
				flag: _this.lijiyuyue == '1' ? flag : '预约下单',
				isRemainingSum: payType
			}
			console.log(JSON.stringify(formData) + '111')
			this.$http
				.ajax({
					url: '/pay/unifiedOrder',
					params: formData
				})
				.then((res) => {
					console.log(res + 'tijiao')
					uni.hideLoading()
					if (res.code == 200) {
						if (res.data) {
							uni.requestPayment({
								provider: 'wxpay',

								timeStamp: res.data.timeStamp,
								nonceStr: res.data.nonceStr,
								package: res.data.package,
								signType: 'MD5',
								paySign: res.data.paySign,

								success: (e) => {
									uni.reLaunch({
										url:
											'./orderDetail?orderId=' +
											res.orderId +
											'&type=' +
											(flag == '预约下单' ? '1' : '2') +
											'&orderState=' +
											(flag == '预约下单' ? '已预约' : '服务中')
									})
								},
								fail: (e) => {
									_this.$api.msg('支付失败')
								}
							})
						} else {
							uni.setStorageSync('gzbhOpen', res.gzbh)
							uni.setStorageSync('xmbhOpen', res.xmbh)
							uni.reLaunch({
								url:
									'./orderDetail?orderId=' +
									res.orderId +
									'&type=' +
									(flag == '预约下单' ? '1' : '2') +
									'&orderState=' +
									(flag == '预约下单' ? '已预约' : '服务中')
							})
						}
					} else {
						this.$api.msg(res.msg)
					}
				})
		},
		getAddressList(ddstatus) {
			const gzbh = getApp().globalData.gzbh
			// console.log('ddstatus'+ddstatus);QN025648274
			this.$http
				.ajax({
					url: '/Cabinet/list',
					params: {
						lat: getApp().globalData.latitude,
						lng: getApp().globalData.longitude,
						gzbh: gzbh.replace(/'/g, '') // :'QN025648274'//:getApp().globalData.gzbh)
					}
				})
				.then((res) => {
					if (res.code == 0) {
						if (res.data.length > 0) {
							this.addressInfo.phone = res.data[0].phone
							this.addressInfo.text = res.data[0].address
						}
					} else {
						this.$api.msg(res.msg)
					}
				})
		}
	}
}
</script>

<style scoped lang="scss">
.pay-box {
	width: 750rpx;
	background: #f7f7f7;
	border-radius: 25rpx 25rpx 0rpx 0rpx;
	padding: 52rpx 27rpx 0;
	padding-bottom: calc(constant(safe-area-inset-bottom) + 30rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 30rpx);
	position: relative;

	.box-item {
		width: 696rpx;
		height: 146rpx;
		background: #ffffff;
		border-radius: 25rpx;
		padding-left: 42rpx;
		padding-right: 35rpx;
		margin-bottom: 20rpx;
	}

	.cz-btn {
		width: 107rpx;
		height: 62rpx;
		background: linear-gradient(0deg, #4082ff, #74a4ff);
		border-radius: 5rpx;
	}

	.ml30 {
		margin-left: 30rpx;
	}

	.close-btn {
		position: absolute;
		right: 40rpx;
		top: 30rpx;
		z-index: 99;
		width: 60rpx;
		height: 60rpx;
	}
}

.wash-box {
	margin: 30rpx auto 0;
	padding: 20rpx 32rpx;
	width: 686rpx;
	background: #ffffff;
	box-shadow: 0rpx 6rpx 12rpx rgba(64, 130, 253, 0.3);
	border-radius: 24rpx;
}

.btn-group {
	width: 750rpx;
	height: calc(constant(safe-area-inset-bottom) + 100rpx);
	height: calc(env(safe-area-inset-bottom) + 100rpx);
	background: #ffffff;
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 10;

	.con-btn {
		width: 750rpx;
		height: 100rpx;
		background: rgba(255, 255, 255, 1);
		padding: 0 32rpx;

		.btn-box {
			width: 180rpx;
			height: 70rpx;
			background: #4082fd;
			border-radius: 35rpx;
		}
	}
}

.info-box {
	padding: 20rpx 32rpx;

	.red-box {
		padding: 8rpx 25rpx;
		background: #f9b9bc;
		border-radius: 20rpx;
		margin-right: 10rpx;
		font-size: 24rpx;
		line-height: 24rpx;
		color: #ea4d51;
	}

	.green-box {
		color: rgba(64, 130, 253, 1);
		background: rgba(64, 130, 253, 0.39);
	}
}

.container {
	padding: 0;
	background-color: #ffffff;
	padding-bottom: 100rpx;
	padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);

	.top-nav {
		width: 750rpx;
		background: #ffffff;
		padding: 20rpx 32rpx;
		border-bottom: 1rpx solid #aeaeae;
	}

	.order-item {
		padding: 30rpx 32rpx 0;

		.item-list {
			padding: 25rpx 0;
			border-bottom: 1rpx solid #aeaeae;
		}
	}
}

.customerName {
	flex: 1;
	margin-left: 20rpx;
	display: flex;
	align-items: center;
	.dateclass {
		font-size: 26rpx;
		color: blue;
	}
}
</style>
